<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { exportToExcel } from '/@/utils/exportToExcel';
import { ElMessage,FormInstance, UploadInstance } from 'element-plus';
import SearchModel from '/@/views/sms/component/search-model.vue';
import {getVisitorVideoApi} from '/@/api/sms/HazardousChemicalsInterface';
import axios from 'axios';
import { getProcessTemplateApi } from '/@/api/workFlow';

//表单
const visitorList = ref([]);

//新增
const showDialogVisible = ref(false);
const ruleForm: any = reactive({
	file: '',
	i_Validity: '1',
	n_FlcFlowschemeId: '',
});

/***** searchClick 查询按钮 *****/
const searchClick = () => {
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			let id = searInfo.value[i];
			init(id);
		});
	}
};

/***** resetClick 重置按钮 *****/
const resetClick = () => {
	searInfo.value = {};
	initInfoFun();
	init();
};

const init = (id?: string) => {
	axios
		.post('http://8.129.209.198:39052/SMS/SMSVistorHistory/Query', {
			idCard: id || '',
		})
		.then((res) => {
			console.log(res);
			visitorList.value = res.data || [];
		});
};

const options1 = ref([]);
onMounted(async () => {
	await init();
	await initInfoFun();

	const res = await getProcessTemplateApi({ SchemeTypeCode: 'fklfsq' });
	options1.value = res.data.map((item: any) => {
		return {
			label: item.name,
			value: item.id,
		};
	});
});

/***** addNodeClick 新增 *****/
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

/*** cancelUseClick  弹窗取消事件 */
const cancelUseClick = () => {
	showDialogVisible.value = false;
	ruleForm.file = '';
	ruleForm.i_Validity = '1';
	ruleForm.n_FlcFlowschemeId = '';
	fileList.value = [];
	upload.value!.clearFiles();
};

/*** controlUseClick  弹窗提交事件 */
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if(!ruleForm.file.length) return ElMessage.error('请上传视频');
	await formEl.validate((valid, fields) => {
		if (valid) {
			getVisitorVideoApi(ruleForm).then((res) => {
				console.log(res);
				cancelUseClick()
			});
		} else {
			console.log('error submit!', fields);
		}
	});
};

/*** ruleFormRef  表单校验 */
const ruleFormRef = ref();
const rules = reactive({
	i_Validity: [{ required: true, message: '内容不能为空', trigger: 'blur' },{pattern:/^[1-9]\d*$/,message:'请输入正整数',trigger: 'blur'}],
	n_FlcFlowschemeId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});

//上传视频
const upload = ref<UploadInstance>();
const fileList = ref([]);
const handleChange = (uploadFile:any) => {
	const videoType = uploadFile.name.split('.')[1];
	if (videoType != 'mp4') return ElMessage.error('请上传mp4格式的视频');
	console.log(uploadFile);
	ruleForm.file =[ uploadFile.raw]
};
/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'idCard', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'idCard', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '身份证号', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};
const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};
/*** 截取日期格式方法 */
const formatDate = (row: any, column: any) => {
	// 获取单元格数据
	let data = row[column.property];
	if (data == null) {
		return '-';
	}
	if (data === '1900-01-01 00:00:00') {
		return '-';
	}
	let dt = new Date(data);
	let month = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
	let date = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
	return dt.getFullYear() + '-' + month + '-' + date;
};

/*** ================================= 导出数据函数操作 ================================= */
const excelRef: any = ref(null);
const handleExport = () => {
	if (excelRef.value) {
		if (excelRef.value.data.length !== 0) {
			let tableExcel: any = [];
			let tableArr = excelRef.value.data;
			tableArr.map((item: any) => {
				let tableObj: any = {};
				tableObj['姓名'] = item.v_Name ? item.v_Name : '-';
				tableObj['供应商类型'] = item.providerType ? item.providerType : '-';
				tableObj['停车区域'] = item.parkArea ? item.parkArea : '-';
				tableObj['车牌号'] = item.licensePlate ? item.licensePlate : '-';
				tableObj['证件类型'] = item.idType ? item.idType : '-';
				tableObj['身份证号'] = item.idCard ? item.idCard : '-';
				tableObj['来访公司'] = item.visitingCompany ? item.visitingCompany : '-';
				tableObj['来访开始时间'] = item.beginTime ? item.beginTime : '-';
				tableObj['来访结束时间'] = item.endTime ? item.endTime : '-';
				tableObj['具体工作内容'] = item.contet ? item.contet : '-';
				tableObj['到访区域'] = item.travelArea ? item.travelArea : '-';
				tableObj['流程模板'] = item.schemeId ? item.schemeId : '-';
				tableObj['接待人员'] = item.clerk ? item.clerk : '-';
				tableObj['是否观看视频'] = item.b_IsWatch ? item.b_IsWatch : '-';
				tableExcel.push(tableObj);
			});
			exportToExcel(tableExcel, '访客记录.xlsx');
		} else {
			ElMessage({
				type: 'error',
				message: '暂无数据导出',
			});
		}
	}
};
</script>

<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<el-form-item>
							<el-button v-if="$hasPer('visitorManagement1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('visitorManagement2:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="visitorList" class="w-h-100" style="width: 100%" border element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="providerType" label="供应商类型" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_Name" label="姓名" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="idType" label="中国大陆" align="center" />
										<el-table-column min-width="140" :show-overflow-tooltip="true" label="身份证号" align="center">
											<el-table-column min-width="140" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="idCard" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.idCard }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="visitingCompany" label="来访公司" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="travelArea" label="到访区域" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="beginTime" label="来访开始时间" :formatter="formatDate" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="endTime" label="来访结束时间" :formatter="formatDate" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="contet" label="具体工作内容" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="clerk" label="接待人员" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="schemeIdName" label="流程模板" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="b_IsWatch" label="是否观看视频" align="center">
											<template #default="scope">
												<template v-if="scope.row.b_IsWatch == 1">是</template>
												<template v-else>否</template>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="停车区域" align="center">
											<template #default="scope">
												<span v-if="scope.row.parkArea">{{ scope.row.parkArea }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="车牌号" align="center">
											<template #default="scope">
												<span v-if="scope.row.licensePlate">{{ scope.row.licensePlate }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="180" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" fixed="right" align="center">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" class="clear-bg" text> 重置 </el-button>
												</template>
												<template #default="{ row }">
													<div class="operate-s">-</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start"></div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" title="新增" width="50%" @close="cancelUseClick">
			<el-form label-width="120px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="n_FlcFlowschemeId" label="流程模板">
							<el-select v-model="ruleForm.n_FlcFlowschemeId" class="m-2" placeholder="请选择流程模板" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="i_Validity" label="观看有效期(月)">
							<el-input-number v-model="ruleForm.i_Validity" :min="1" :max="12"  placeholder="请填写观看有效期" style="width: 100%;"/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-divider content-position="left"> 视频上传 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-upload ref="upload" action="#" v-model:file-list="fileList" :limit="1" :on-change="   (file: any) => { handleChange(file) }" :auto-upload="false">
							<template #trigger>
								<el-button type="primary">选择视频</el-button>
							</template>
							<template #tip>
								<div class="el-upload__tip text-red">请选择mp4格式的视频，且只能上传一个视频，选择视频后确认信息无误后请点击确认按钮保存视频以及相关信息</div>
							</template>
						</el-upload>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss">
@import '../../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
